import whois
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from mail import sendmail
from models import Domain_List

engine = create_engine(
    "mysql+pymysql://account:password@dbhost:3306/test_domain?charset=utf8mb4", #数据库设置，请自行修改
    echo=False)

Session = sessionmaker(bind=engine)
session = Session()
now = datetime.now()


def check_all():
    all_item = session.query(Domain_List).filter_by(is_check=True).all()
    for item in all_item:
        try:
            w = whois.whois(item.domain)
            if type(w.expiration_date) is datetime:
                res = str(w.expiration_date).split(" ")[0]
            else:
                res = str(w.expiration_date[0]).split(" ")[0]
            info = session.query(Domain_List).filter_by(id=item.id).first()
            info.expir = res
            session.commit()
        except Exception as e:
            print(e)


def check_expir():
    all_item = session.query(Domain_List).filter_by(is_discard=False).all()
    for item in all_item:
        expir = datetime.strptime(item.expir, "%Y-%m-%d")
        delta = expir - now
        if delta.days <= 91:
            subject = "[DomainName Expiration Warning] " + item.domain + " 域名即将过期！"
            tpl = "<p>域名：{}</p><p>到期时间：{}</p><p>过期天数剩余：{}天</p><p>域名用途：{}</p><p>域名所属：{}</p><p>域名注册商：{}</p>"
            body = tpl.format(item.domain, item.expir, delta.days, item.used, item.owner, item.regist)
            tt = datetime.strftime(now, '%Y-%m-%d')
            body = body + "<p>" + tt + "</p>"
            sendmail(subject=subject, body=body)
            print(item.domain,delta.days)


if __name__ == '__main__':
    check_all()
    check_expir()
